package com.elitel.frame.base.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.elitel.common.core.log.annotation.Log;
import com.elitel.common.core.log.enums.BusinessType;
import com.elitel.common.utils.StringUtils;
import com.elitel.frame.base.component.quartz.QuartzScheduler;
import com.elitel.frame.base.component.quartz.SearchServiceTask;
import com.elitel.frame.base.service.*;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.constant.DictionaryConstant;
import com.elitel.frame.main.entity.ext.BaseQueryfieldcacheExt;
import com.elitel.frame.main.entity.vo.*;
//import com.netflix.discovery.converters.Auto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elitel.common.log.LogCtrl;
import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.main.dao.ext.ExtCfgExtendMapper;
import com.elitel.frame.main.entity.ext.CfgExtendExt;

/**
 * @Description 单表配置服务
 * @author guoyanfei
 */
@Controller
@RequestMapping("/system/singleTable")
public class SingleTableController {
	@Autowired
	private CfgExtendService cfgExtendService;
	@Autowired
	private CfgTableService cfgTableService;
	@Autowired
	private CfgDbService cfgDbService;
	@Autowired
	private BaseShowfieldService baseShowfieldService;
	@Autowired
	private CfgFieldService cfgFieldService;
	@Autowired
	private QuartzScheduler quartzScheduler;
	@Autowired
	private SearchServiceTask searchServiceTask;
	@Autowired
	BaseQueryfieldcacheService baseQueryfieldcacheService;
	@Autowired
	private SysPrjServiceService sysPrjServiceService;

	private static final Logger logger = LoggerFactory.getLogger(DataConfigController.class);

	/**
	 * @Title: getSingleTableByPage
	 * @Description: TODO(分页查询单表配置服务信息)
	 * @param pageNo(当前页)、pageSize(页大小)、dbkey(数据库主键)
	 * @author guoyanfei
	 * @return PageResponseVo<CfgExtendExt>(分页显示bootstrap Table数据)
	 * @throws
	 */
	@RequestMapping("/list")
	@ResponseBody
	public PageResponseVo<CfgExtendExt> getSingleTableByPage(
			HttpServletRequest request, HttpServletResponse response)
	{
		PageResponseVo<CfgExtendExt> pagelist = new PageResponseVo<CfgExtendExt>();
		try {
			PageRequestVo<CfgExtend> pr = new PageRequestVo<CfgExtend>();
			int pageNo = Integer.valueOf(request.getParameter("pageNo")).intValue();
			int pageSize = Integer.valueOf(request.getParameter("pageSize")).intValue();
			String dbkey = request.getParameter("dbkey");
			pr.setSearchContent(dbkey);
			pr.setPageNo(pageNo);
			pr.setPageSize(pageSize);
			pagelist = cfgExtendService.getListByPage(pr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}

		return pagelist;
	}


	/**
	 * @Title: getTreeList
	 * @Description: TODO(查询树形结构数据库信息)
	 * @param
	 * @author guoyanfei
	 * @return List<ZTreeDataModelVo>(zTree结构数据)
	 * @throws
	 */
	@RequestMapping("/treeList")
	@ResponseBody
	public List<ZTreeDataModelVo> getTreeList(
			HttpServletRequest request, HttpServletResponse response)
	{
		List<ZTreeDataModelVo> zTreeDataModelVos = new ArrayList<ZTreeDataModelVo>();
		try {
			zTreeDataModelVos = cfgExtendService.getTreeCfgExtendList();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return zTreeDataModelVos;
	}

	/**
	 * @description 查询所有数据源
	 * @return Cfgdb集合
	 * @author guoyanfei
	 * @date 2017/11/29
	 */
	@RequestMapping("/getAllDataSource")
	@ResponseBody
	public List<CfgDb> getAllDataSource(HttpServletRequest request){
		List<CfgDb> cfgDbs = new ArrayList<CfgDb>();
		try {
			cfgDbs = cfgDbService.getAllListCfgDb();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}

		return cfgDbs;
	}

	/**
	 * @Title: getTableList
	 * @Description: TODO(通过数据库主键查询所有表信息)
	 * @param dbkey(数据库主键)
	 * @author guoyanfei
	 * @return List<CfgTable>(表信息集合)
	 * @throws
	 */
	@RequestMapping("/tableByKey")
	@ResponseBody
	public List<CfgTable> getTableList(HttpServletRequest request)
	{
		List<CfgTable> cfgTables = new ArrayList<CfgTable>();
		try {
			String dbkey = request.getParameter("dbkey");
			cfgTables = cfgTableService.getListbyConn(dbkey);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return cfgTables;
	}

	/**
	 * @Title: insertSingleTable
	 * @Description: TODO(新增单表配置服务信息)
	 * @param CfgExtend(单表配置服务)
	 * @author guoyanfei
	 * @return int(插入结果)
	 * @throws
	 */
	@RequestMapping("/addSingleTable")
	@ResponseBody
	public Object insertSingleTable(@RequestBody CfgExtendExt cfgExtendExt)
	{
		JsonResult jsonResult = checkService(cfgExtendExt);
		if (jsonResult != null) return jsonResult;

		Integer result=0;
		try {
			result=cfgExtendService.insertCfgExtendandSysprjs(cfgExtendExt);
			//默认新增显示所有列
			List<ShowFieldVo> showFieldVos = baseShowfieldService.getShowfieldByServiceId(cfgExtendExt.getGuid(), DictionaryConstant.ServiceType_SingleTableService + "", "");
			List<BaseShowfield> baseShowfieldList = new ArrayList<>();
			if(XCommonUtils.isNotEmpty(showFieldVos)){
				for (ShowFieldVo showFieldVo: showFieldVos) {
					BaseShowfield baseShowfield = new BaseShowfield();
					baseShowfield.setGuid(UUID.randomUUID().toString());
					baseShowfield.setServicetype(1);
					baseShowfield.setServiceid(cfgExtendExt.getGuid());
					baseShowfield.setFieldaddonsguid(showFieldVo.getFieldguid());
					baseShowfield.setMasterdetailid("");
					baseShowfieldList.add(baseShowfield);
				}
				result += baseShowfieldService.addShowfield(baseShowfieldList);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return result;
	}

	private JsonResult checkService(CfgExtendExt cfgExtendExt) {
		String serviceCode = cfgExtendExt.getGuid();
		boolean b = sysPrjServiceService.serviceCodeExist(null, serviceCode);
		if (b){
			JsonResult jsonResult = new JsonResult();
			jsonResult.setSuccess(false);
			jsonResult.setMsg("服务编码已存在，请重新填写！");
			return jsonResult;
		}
		if (StringUtils.isNotEmpty(cfgExtendExt.getApiPath())){
			boolean flag = sysPrjServiceService.selectServiceApiCode(cfgExtendExt.getApiPath());
			if (flag){
				JsonResult jsonResult = new JsonResult();
				jsonResult.setSuccess(false);
				jsonResult.setMsg("服务调用地址已存在，请重新填写！");
				return jsonResult;
			}
		}
		return null;
	}

	/**
	 * @Title: updateSingleTable
	 * @Description: TODO(修改单表配置服务信息)
	 * @param CfgExtend(单表配置服务)
	 * @author guoyanfei
	 * @return int(修改结果)
	 * @throws
	 */
	@RequestMapping("/updateSingleTable")
	@ResponseBody
	@Log(title = "修改单表配置服务", businessType = BusinessType.UPDATE)
	public int updateSingleTable(@RequestBody CfgExtendExt cfgExtendExt)
	{
		int result =0;
		try {
			CfgExtend cfgExtend = new CfgExtend();
			cfgExtend.setGuid(cfgExtendExt.getGuid());
			cfgExtend.setDbKey(cfgExtendExt.getDbKey());
			cfgExtend.setDtConfigId(cfgExtendExt.getDtConfigId());
			cfgExtend.setServicename(cfgExtendExt.getServicename());
			cfgExtend.setResponseMode(cfgExtendExt.getResponseMode());
			if(cfgExtendExt.getIsPagination() !=null && !cfgExtendExt.getIsPagination().equals("")){
				cfgExtend.setIspagination(Integer.valueOf(cfgExtendExt.getIsPagination()));
			}
			cfgExtend.setRemark(cfgExtendExt.getRemark());
			if(cfgExtendExt.getSysCatch() !=null && !cfgExtendExt.getSysCatch().equals("")){
				cfgExtend.setSyscatch(Integer.valueOf(cfgExtendExt.getSysCatch()));
			}
			if(cfgExtendExt.getCatchtime() != null && !cfgExtendExt.getCatchtime().equals("")){
				cfgExtend.setCatchtime(Integer.valueOf(cfgExtendExt.getCatchtime()));
			}

			cfgExtend.setTimeDelay(cfgExtendExt.getTimeDelay());

			result = cfgExtendService.updateData(cfgExtend,cfgExtendExt);
			if(result > 0) {
				String serviceType = "singleTableServer";
				//清除该服务的任务调度
				quartzScheduler.deleteJobs(cfgExtend.getGuid());
				List<BaseQueryfieldcacheExt> list = baseQueryfieldcacheService.queryCacheFieldGroup(cfgExtend.getGuid(), serviceType);
				if(null != list && list.size() > 0) {
					for (BaseQueryfieldcacheExt group: list) {
						//重新添加任务调度
						searchServiceTask.startQueryDataByCacheConfigScheduler(cfgExtend.getGuid(), serviceType, group.getParametergroup());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * @Title: deleteSingleTable
	 * @Description: TODO(批量删除单表配置服务信息)
	 * @param guids(主键集合以','隔开)
	 * @author guoyanfei
	 * @return
	 * @throws
	 */
	@RequestMapping("/batchDeleteSingleTable")
	@ResponseBody
	public void deleteSingleTable(HttpServletRequest request)
	{
		try {
			String guids = request.getParameter("guids");
			String[] guidarray = guids.split(",");
			List<String> guidList = Arrays.asList(guidarray);
			for (String string : guidList) {
				cfgExtendService.deleteCfgExtendByguid(string);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}

	}


	/**
	 * @Title: deleteSingleTable
	 * @Description: TODO(通过主键标识查询单表配置服务信息)
	 * @param guid(主键标识)
	 * @author guoyanfei
	 * @return CfgExtend实体
	 * @throws
	 */
	@RequestMapping("/selectDataByGuid")
	@ResponseBody
	public CfgExtend selectByGuid(HttpServletRequest request)
	{
		CfgExtend cfgExtend= new CfgExtend();
		try {
			String guid = request.getParameter("guid");
			cfgExtend = cfgExtendService.selectByPrimaryKey(guid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return cfgExtend;
	}

	/**
	 * @Title: isExistByguid
	 * @Description: TODO(判断guid是否存在)
	 * @param guid(主键标识)
	 * @author guoyanfei
	 * @return true或false
	 * @throws
	 */
	@RequestMapping("/isExistByguid")
	@ResponseBody
	public boolean isExistByguid(HttpServletRequest request){
		boolean result = false;
		try {
			String guid = request.getParameter("guid");
			result = cfgExtendService.existByguid(guid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}

		return result;
	}


}
